/**
 * 页面 cookie 控制管理
 * @author laan
 * 修改整理：ibio
 * 2009-6-2 16:09
 */
package com.ibio8.javascript {
	import flash.external.ExternalInterface;
	/**
	 * 页面 cookie 控制管理。
	 * 
	 * <p>
	 * 从 laan 那里整理而来的一个工具类。
	 * </p>
	 * <b>此类的作者是 laan。</b>
	 * @private
	 */
	public class Cookie {
		init();
		
		/**
		 * 设置 cookie
		 * @param name		名称
		 * @param value		值
		 * @param expires	过期时间
		 * @param security	是否加密
		 */
		public static function setCookie(name:String, value:String, expires:uint = 0, security:Boolean = false):void {
			if (ExternalInterface.available) {
				try {
					ExternalInterface.call("js_setCookie", name, value, expires, security);
				}catch (e:Error) {
					trace("Cookie::setCookie->", e.message);
				}
			}
		}
		
		/**
		 * 获取 cookie
		 * @param name	名称
		 * @return		cookie
		 */
		public static function getCookie(name:String):String {
			if (ExternalInterface.available) {
				try {
					return ExternalInterface.call("js_getCookie", name);
				}catch (e:Error) {
					trace("Cookie::getCookie->", e.message);
				}
			}
			return null;
		}
		
		/**
		 * 删除 cookie
		 * @param name	名称
		 */
		public static function deleteCookie(name:String):void {
			if (ExternalInterface.available) {
				try {
					ExternalInterface.call("js_deleteCookie", name);
				}catch (e:Error) {
					trace("Cookie::deleteCookie->", e.message);
				}
			}
		}
		
		/** @private **/
		protected static function init():void {
			var str:String = "";
			//设置 cookie
			str += 'function js_setCookie(name, value, expires, security) {var str = name + "=" + escape(value);if (expires != 0) {str += ";expires=" + new Date(expires).toUTCString() + "";} if (security) {str += ";secure";}document.cookie = str;}';
			//获取 cookie
			str += 'function js_getCookie(name) {var cookie = new String(document.cookie);var arr = cookie.match(new RegExp(";?" +name + "=([^;]*)"));if(arr != null) {return unescape(arr[1]);} return null;}';
			//删除 cookie
			str += 'function js_deleteCookie(name) {var d = new Date();d.setTime(d.getTime() - 1);var value = js_getCookie(name);if(value != null) {document.cookie = name + "=" + escape(value) + ";expire=" + d.toUTCString();}}';
			if (ExternalInterface.available) {
				try {
					ExternalInterface.call("eval", str);
				}catch (e:Error) {
					trace("Cookie::init->", e.message);
				}
			}
		}
	}
}